﻿using System;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows.Threading;

namespace ActionScheduler.Lib {
    internal class ActionSchedulerAction {
        //Start Properties
        public DateTime StartAction { get; set; }
        public Action Action { get; set; }
        public bool RunOnGuiThread { get; set; }
        public string ScopeKey { get; set; }
        public string ActionKey { get; set; }
        public Action OnCompleted { get; set; }
        public bool RunOnCompletedOnGuiThread { get; set; }

        //State Properties
        public bool IsRunning { get; set; }
        public DispatcherOperation GuiWorker { get; set; }
        public Task TaskWorker { get; set; }

        //Actions
        internal void WasAborted(object sender, EventArgs e) {
            ActionScheduler.Instance.RemoveAction(this);
        }

        internal void WasCompleted(object sender, EventArgs e) {
            WasCompleted();
        }

        internal void WasCompleted() {
            ActionScheduler.Instance.RemoveAction(this);
            if (OnCompleted != null) {
                ActionScheduler.ScheduleAction(OnCompleted, RunOnCompletedOnGuiThread, ScopeKey);
            }
        }

        public void OnWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
            WasCompleted();
        }

        public void DoBackgroundWork() {
            Action.Invoke();
        }
    }
}
